<template>
  <div style="padding: 20px">
    <el-input v-model="message" placeholder="输入消息" style="width: 300px" @keyup.enter.native="send" />
    <el-button type="primary" @click="send">发送</el-button>
    <el-button type="success" @click="connect" >连接websocket</el-button>
    <el-button type="danger"  @click="disconnect">断开websocket</el-button>
    <el-divider>消息记录</el-divider>
    <div v-for="(msg, index) in messages" :key="index">{{ msg }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ws: null,
      message: '',
      messages: []
    };
  },
  mounted() {
    this.connect();
  },
  beforeDestroy() {
    if (this.ws) this.ws.close();
  },
  methods: {
    connect() {
      this.ws = new WebSocket('ws://localhost:8080/websocket');

      this.ws.onopen = () => {
        this.messages.push('WebSocket连接成功');
      };

      this.ws.onmessage = (event) => {
        this.messages.push('收到：' + event.data);
      };

      this.ws.onclose = () => {
        this.messages.push('WebSocket连接关闭');
      };

      this.ws.onerror = (err) => {
        this.messages.push('WebSocket连接异常');
        console.error(err);
      };
    },
    disconnect() {
      if (this.ws) {
        this.ws.close(1000, "用户主动断开");
        this.ws = null;
      }
    },
    send() {
      if (this.ws && this.message) {
        this.ws.send(this.message);
        this.messages.push('发送：' + this.message);
        this.message = '';
      }else{
        alert("未连接websocket或消息为空")
      }
    }
  }
};
</script>
